# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import os
import random
import time
import math
from functools import partial

import numpy as np
import paddle
from paddle.io import DataLoader

import paddlenlp as ppnlp
from paddlenlp.transformers import LinearDecayWithWarmup
from paddlenlp.metrics import ChunkEvaluator
from paddlenlp.datasets import load_dataset
from paddlenlp.transformers import BertForTokenClassification, BertTokenizer, ErnieForTokenClassification,ErnieTokenizer
from paddlenlp.data import Stack, Tuple, Pad, Dict
from utils import convert_example_to_feature, parse_result

from model import ErnieCrf

parser = argparse.ArgumentParser()

# yapf: disable
# parser.add_argument("--model_name_or_path", default=None, type=str, required=True, help="Path to pre-trained model or shortcut name selected in the list: " + ", ".join(list(BertTokenizer.pretrained_init_configuration.keys())))
parser.add_argument("--num_epoch", type=int, default=3, help="Number of epoches for fine-tuning.")
parser.add_argument("--output_dir", default=None, type=str, required=True, help="The output directory where the model predictions and checkpoints will be written.")
parser.add_argument("--max_seq_len", default=512, type=int, help="The maximum total input sequence length after tokenization. Sequences longer than this will be truncated, sequences shorter will be padded.")
parser.add_argument("--tag_path", type=str, default=None, help="tag set path")
parser.add_argument("--train_data", type=str, default=None, help="train_data set path")
parser.add_argument("--batch_size", default=8, type=int, help="Batch size per GPU/CPU for training.")
parser.add_argument("--learning_rate", default=5e-5, type=float, help="The initial learning rate for Adam.")
parser.add_argument("--weight_decay", default=0.0, type=float, help="Weight decay if we apply some.")
parser.add_argument("--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer.")
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
parser.add_argument("--num_train_epochs", default=3, type=int, help="Total number of training epochs to perform.", )
parser.add_argument("--max_steps", default=-1, type=int, help="If > 0: set total number of training steps to perform. Override num_train_epochs.",)
parser.add_argument("--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.")
parser.add_argument("--logging_steps", type=int, default=10, help="Log every X updates steps.")
parser.add_argument("--save_steps", type=int, default=1000, help="Save checkpoint every X updates steps.")
parser.add_argument("--seed", type=int, default=42, help="random seed for initialization")
parser.add_argument("--n_gpu", type=int, default=1, help="number of gpus to use, 0 for cpu.")
parser.add_argument('--device', choices=['cpu', 'gpu'], default="gpu", help="Select which device to train model, defaults to gpu.")

# yapf: enable


class NERDataLoader(paddle.io.Dataset):
    """DuEventExtraction"""
    def __init__(self, data_path, tag_path):
        super(NERDataLoader, self).__init__()
        self.label_vocab = load_dict(tag_path)
        self.word_ids = []
        self.label_ids = []
        with open(data_path, 'r', encoding='utf-8') as fp:
            # skip the head line
            next(fp)
            for line in fp.readlines():
                words, labels = line.strip('\n').split('\t')
                words = words.split('\002')
                labels = labels.split('\002')
                self.word_ids.append(words)
                self.label_ids.append(labels)
        self.label_num = max(self.label_vocab.values()) + 1

    def __len__(self):
        return len(self.word_ids)

    def __getitem__(self, index):
        return self.word_ids[index], self.label_ids[index]


def load_dict(dict_path):
    """load_dict"""
    vocab = {}
    for line in open(dict_path, 'r', encoding='utf-8'):
        value, key = line.strip('\n').split('\t')
        vocab[key] = int(value)
    return vocab


def tokenize_and_align_labels(example, tokenizer, no_entity_id,
                              max_seq_len=512):
    labels = example['labels']
    example = example['tokens']
    tokenized_input = tokenizer(
        example,
        return_length=True,
        is_split_into_words=True,
        max_seq_len=max_seq_len)

    # -2 for [CLS] and [SEP]
    if len(tokenized_input['input_ids']) - 2 < len(labels):
        labels = labels[:len(tokenized_input['input_ids']) - 2]
    tokenized_input['labels'] = [no_entity_id] + labels + [no_entity_id]
    tokenized_input['labels'] += [no_entity_id] * (
        len(tokenized_input['input_ids']) - len(tokenized_input['labels']))
    return tokenized_input




def set_seed(args):
    """sets random seed"""
    random.seed(args.seed)
    np.random.seed(args.seed)
    paddle.seed(args.seed)


def do_train(args):
    paddle.set_device(args.device)
    world_size = paddle.distributed.get_world_size()
    rank = paddle.distributed.get_rank()
    if world_size > 1:
        paddle.distributed.init_parallel_env()

    set_seed(args)

    no_entity_label = "O"
    ignore_label = -1

    tokenizer = ErnieTokenizer.from_pretrained("ernie-1.0")
    label_map = load_dict(args.tag_path)
    id2label = {val: key for key, val in label_map.items()}
    # model = ErnieForTokenClassification.from_pretrained("ernie-1.0", num_classes=len(label_map))
    model = ErnieCrf(num_labels=len(label_map), pre_trained_model="ernie-1.0")
    model = paddle.DataParallel(model)

    print("============start train==========")
    train_ds = NERDataLoader(args.train_data, args.tag_path)
    print(len(train_ds))

    trans_func = partial(
        convert_example_to_feature,
        tokenizer=tokenizer,
        label_vocab=train_ds.label_vocab,
        max_seq_len=args.max_seq_len,
        no_entity_label=no_entity_label,
        ignore_label=ignore_label,
        is_test=False)

    # print(tokenizer.pad_token_id)
    # batchify_fn = lambda samples, fn=Dict({
    #     'input_ids': Pad(axis=0, pad_val=tokenizer.pad_token_id, ret_length=args.max_seq_length),  # input
    #     'token_type_ids': Pad(axis=0, pad_val=tokenizer.pad_token_type_id, ret_length=args.max_seq_length),  # segment
    #     'seq_len': Stack(),  # seq_len
    #     'labels': Pad(axis=0, pad_val=ignore_label)  # label
    # }): fn(samples)
    # pad_fn = Tuple(
    #     Pad(axis=0, pad_val=tokenizer.vocab[tokenizer.pad_token], dtype='int32'),  # input ids
    #     Pad(axis=0, pad_val=tokenizer.vocab[tokenizer.pad_token], dtype='int32'),  # token type ids
    #     Stack(dtype='int64'),  # sequence lens
    #     Pad(axis=0, pad_val=ignore_label, dtype='int64')  # labels
    # )
    # tmp_database = pad_fn(list(map(trans_func, train_ds)))

    batchify_fn = lambda samples, fn=Tuple(
        Pad(axis=0, pad_val=tokenizer.vocab[tokenizer.pad_token], dtype='int32'),  # input ids
        Pad(axis=0, pad_val=tokenizer.vocab[tokenizer.pad_token], dtype='int32'),  # token type ids
        Stack(dtype='int64'),  # sequence lens
        Pad(axis=0, pad_val=ignore_label, dtype='int64')  # labels
    ): fn(list(map(trans_func, samples)))

    def padding_func(samples):
        # ignore_label = -1
        pd_fn = Tuple(
            Pad(axis=0, pad_val=tokenizer.vocab[tokenizer.pad_token], dtype='int32'),  # input ids
            Pad(axis=0, pad_val=tokenizer.vocab[tokenizer.pad_token], dtype='int32'),  # token type ids
            Stack(dtype='int64'),  # sequence lens
            Pad(axis=0, pad_val=ignore_label, dtype='int64')  # labels
        )
        tmp = pd_fn(list(map(trans_func, samples)))
        return tmp

    batch_sampler = paddle.io.DistributedBatchSampler(train_ds, batch_size=args.batch_size, shuffle=True)
    train_loader = paddle.io.DataLoader(
        dataset=train_ds,
        batch_sampler=batch_sampler,
        collate_fn=padding_func)

    print(len(train_loader))
    # train_data_loader = DataLoader(
    #     dataset=train_ds,
    #     collate_fn=batchify_fn,
    #     num_workers=0,
    #     batch_sampler=train_batch_sampler,
    #     return_list=True)

    # test_ds = test_ds.map(trans_func)
    #
    # test_data_loader = DataLoader(
    #     dataset=test_ds,
    #     collate_fn=batchify_fn,
    #     num_workers=0,
    #     batch_size=args.batch_size,
    #     return_list=True)

    # Define the model netword and its loss
    decay_params = [
        p.name for n, p in model.named_parameters()
        if not any(nd in n for nd in ["bias", "norm"])
    ]
    optimizer = paddle.optimizer.AdamW(
        learning_rate=args.learning_rate,
        parameters=model.parameters(),
        weight_decay=args.weight_decay,
        apply_decay_param_fun=lambda x: x in decay_params)
    num_training_steps = len(train_loader) * args.num_epoch

    lr_scheduler = LinearDecayWithWarmup(args.learning_rate, num_training_steps,
                                         args.warmup_steps)

    # loss_fct = paddle.nn.loss.CrossEntropyLoss(ignore_index=ignore_label)

    # metric = ChunkEvaluator(label_list=train_ds.label_vocab.keys(), suffix=False)

    last_step = args.num_train_epochs * len(train_loader)
    current_epoch_step = len(train_loader)

    tic_train = time.time()
    model.train()

    for epoch in range(args.num_train_epochs):
        step = 0
        for idx, (input_ids, token_type_ids, seq_lens, labels) in enumerate(train_loader):
            step += 1

            loss, lengths, labels = model(input_ids, token_type_ids, seq_lens ,labels)
            avg_loss = paddle.mean(loss)
            if step % args.logging_steps == 0:
                print("epoch: %d / %d, step %d /  %d, loss: %f, speed: %.2f step/s" %
                      (epoch, args.num_train_epochs-1, step, current_epoch_step, avg_loss, args.logging_steps / (time.time() - tic_train)))
                tic_train = time.time()
            avg_loss.backward()
            optimizer.step()
            lr_scheduler.step()
            optimizer.clear_grad()
            if step % args.save_steps == 0 or step == last_step:
                if (not args.n_gpu > 1) or paddle.distributed.get_rank() == 0:
                    # evaluate(model, loss_fct, metric, test_data_loader,
                    #          label_num)
                    save_params_path = "model_epoch_%d_%d.pdparams" % (epoch, step)
                    paddle.save(model.state_dict(),
                                os.path.join(args.output_dir, save_params_path))


if __name__ == "__main__":
    args = parser.parse_args()
    # if args.n_gpu > 1:
    #     paddle.distributed.spawn(do_train, args=(args, ), nprocs=args.n_gpu)
    # else:
    do_train(args)
